package com.yc.study.controller;

import com.yc.study.config.file.FileUploadConfig;
import com.yc.study.vo.ImageData;
import com.yc.study.vo.UploadVo;
import io.minio.MinioClient;
import org.apache.commons.io.output.WriterOutputStream;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @author liupeng
 */
@RestController
public class UploadController {

  @Resource private MinioClient minioClient;

  /**
   * 文件上传
   *
   * @param file 上传的文件
   * @return 回调的地址
   */
  @PostMapping("/upload")
  public UploadVo upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
      throws IOException {
    final FileUploadConfig.PathInfo pathInfo = FileUploadConfig.generatePath(file);
    final String realPath = pathInfo.getRealPath();
    IOUtils.copy(file.getInputStream(), new FileOutputStream(realPath));
    return UploadVo.builder()
        .code(0)
        .data(new ImageData(pathInfo.getMappingPath(), file.getOriginalFilename()))
        .build();
  }

  /**
   * 下载文件
   *
   * @param filename 文件名
   */
  @GetMapping("/download2/{filename}")
  public void download(@PathVariable String filename, HttpServletResponse res) throws IOException {
    final FileUploadConfig.PathInfo pathInfo = FileUploadConfig.getPathInfo(filename);
    res.setCharacterEncoding("utf-8");
    res.setContentType("application/force-download");
    res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
    IOUtils.copy(new FileInputStream(pathInfo.getRealPath()), res.getOutputStream());
    res.flushBuffer();
  }
}
